unity health bar

58

unity health bar -

//SCRIPT HealthBar.CS to put on your HealthBar Inspector

using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
  public Image healthBarImage;
  public Player player;
  public void UpdateHealthBar() {
    healthBarImage.fillAmount = Mathf.Clamp(player.health / player.maxHealth, 0, 1f);
  }
}
//____________________________________________________________________________
//SCRIPT Player.CS to put on your Player Inspector

using UnityEngine;
using UnityEngine.UI;
public class Player: MonoBehaviour
{
  public float health, maxHealth;
  public HealthBar healthBar;
  public void TakeDamage(){
    // Use your own damage handling code, or this example one.
    health -= 25;            
    healthBar.UpdateHealthBar();
  }
  void Update(){
    // Example so we can test the Health Bar functionality
    if(Input.GetKeyDown(KeyCode.Space)){
      TakeDamage();
    }
  }
}

Comments

Submit
0 Comments